package cn.thinkcloud.corpwx.worksign.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.qq.weixin.mp.bean.QyWxXmlMessage;
import com.qq.weixin.mp.bean.QyWxXmlResponseBody;

import cn.thinkcloud.corpwx.worksign.component.ScheduledRunnable;

@Controller
@RequestMapping("/contact")
public class ContactController {

	private final static Logger logger = LoggerFactory.getLogger(ContactController.class);

    @Autowired
    @Qualifier("updateAccessToken")
    ScheduledRunnable updateAccessTokenScheduleTask;

    @Value("${wxbiz.corpid}")
    private String corpid;
    @Value("${wxbiz.contact.Token}")
    private String wxbizContactToken;
    @Value("${wxbiz.contact.EncodingAESKey}")
    private String wxbizContactEncodingAESKey;

	/**
	 * 验证接收事件服务器的设置
	 * 请求方式：GET
	 * 请求地址：http://<event-server-uri>?msg_signature=<...>&timestamp=<...>&nonce=<...>&echostr=<ENCRYPT_STR>
	 * @throws AesException 
	 */
	@RequestMapping(value = "/sync", method = RequestMethod.GET)
    @ResponseBody
	public String sync(String msg_signature, String timestamp, String nonce, String echostr, HttpServletResponse response) throws AesException {
		logger.info("/sync:GET");
		logger.info("    signature: " + msg_signature);
		logger.info("    timestamp: " + timestamp);
		logger.info("        nonce: " + nonce);
		logger.info("      echostr: " + echostr);
		logger.info("        token: " + wxbizContactToken);
		
		WXBizMsgCrypt cryptor = new WXBizMsgCrypt(wxbizContactToken, wxbizContactEncodingAESKey, corpid);
		
		String decrypted = cryptor.VerifyURL(msg_signature, timestamp, nonce, echostr);
		
		return decrypted;
	}

	/**
	 * 事件接收
	 * 请求方式：POST
	 * 请求地址：http://<event-server-uri>?msg_signature=<...>&timestamp=<...>&nonce=<...>
	 * @throws AesException 
	 */
	@RequestMapping(value = "/sync", method = RequestMethod.POST)
    @ResponseBody
	public QyWxXmlResponseBody sync(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 微信服务器推送过来的是XML格式。
				
		logger.info("/sync:POST");
		
		String msgSignature = request.getParameter("msg_signature");
		String timeStamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		
		WXBizMsgCrypt cryptor = new WXBizMsgCrypt(wxbizContactToken, wxbizContactEncodingAESKey, corpid);
		
		QyWxXmlMessage wx = QyWxXmlMessage.decryptMsg(cryptor, request.getInputStream(), timeStamp, nonce, msgSignature);

		logger.info("QyWxXmlMessage: {");
		logger.info("    ToUserName: " + wx.getToUserName());
		logger.info("       MsgType: " + wx.getMsgType());
		logger.info("         Event: " + wx.getEvent());
		logger.info("    }");
		
		String responseContent = String.format("Received message from user %s, msgType %s ...",
				wx.getToUserName(), wx.getMsgType());
		
		QyWxXmlResponseBody body = new QyWxXmlResponseBody();
		body.makeResponse(cryptor, responseContent);
		
		return body;
	}
}
